"""
自定义日志配置模块

提供统一的日志记录功能，包括：
1. 基础日志记录
2. HTTP请求/响应日志
3. 数据库操作日志
4. 模型推理日志
5. 性能监控日志

作者: LLM Chat System
版本: 1.0.0
"""

import sys
import time
import traceback
from pathlib import Path
from typing import Optional, Dict, Any
from loguru import logger
from app.core.config import settings


class CustomLogger:
    """自定义日志记录器类"""
    
    def __init__(self, name: str = "app"):
        self.name = name
        self.logger = logger.bind(name=name)
    
    def info(self, message: str, **kwargs):
        """记录信息日志"""
        self.logger.info(message, **kwargs)
    
    def warning(self, message: str, **kwargs):
        """记录警告日志"""
        self.logger.warning(message, **kwargs)
    
    def error(self, message: str, **kwargs):
        """记录错误日志"""
        self.logger.error(message, **kwargs)
    
    def critical(self, message: str, **kwargs):
        """记录严重错误日志"""
        self.logger.critical(message, **kwargs)
    
    def debug(self, message: str, **kwargs):
        """记录调试日志"""
        self.logger.debug(message, **kwargs)
    
    def http_request(self, method: str, path: str, status_code: int, 
                    duration: float, client_ip: str = None, user_agent: str = None):
        """记录HTTP请求日志"""
        extra_info = ""
        if client_ip:
            extra_info += f" - IP: {client_ip}"
        if user_agent:
            extra_info += f" - UA: {user_agent[:50]}..."
        
        self.logger.info(
            f"HTTP请求: {method} {path} - {status_code} - {duration:.3f}s{extra_info}",
            extra={"access": True}
        )
    
    def api_call(self, endpoint: str, method: str, status: str, duration: float = None):
        """记录API调用日志"""
        duration_str = f" - {duration:.3f}s" if duration else ""
        self.logger.info(f"API调用: {method} {endpoint} - {status}{duration_str}")
    
    def database_operation(self, operation: str, table: str, status: str, duration: float = None):
        """记录数据库操作日志"""
        duration_str = f" - {duration:.3f}s" if duration else ""
        self.logger.info(f"数据库操作: {operation} {table} - {status}{duration_str}")
    
    def model_inference(self, model_name: str, input_tokens: int, output_tokens: int, 
                       duration: float, status: str = "成功"):
        """记录模型推理日志"""
        self.logger.info(
            f"模型推理: {model_name} - 输入:{input_tokens} 输出:{output_tokens} - {duration:.3f}s - {status}"
        )
    
    def performance(self, operation: str, duration: float, details: str = None):
        """记录性能监控日志"""
        details_str = f" - {details}" if details else ""
        self.logger.info(f"性能监控: {operation} - {duration:.3f}s{details_str}")
    
    def exception(self, message: str, exc_info: Exception = None):
        """记录异常日志"""
        if exc_info:
            self.logger.error(f"{message}: {str(exc_info)}", exc_info=True)
        else:
            self.logger.error(message, exc_info=True)


def setup_logging():
    """设置日志配置"""
    
    # 移除默认处理器
    logger.remove()
    
    # 创建日志目录
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    # 控制台输出格式
    console_format = (
        "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
        "<level>{message}</level>"
    )
    
    # 文件输出格式
    file_format = (
        "{time:YYYY-MM-DD HH:mm:ss.SSS} | "
        "{level: <8} | "
        "{name}:{function}:{line} | "
        "{message}"
    )
    
    # 添加控制台处理器 - 强制使用DEBUG级别以便查看所有日志
    logger.add(
        sys.stdout,
        format=console_format,
        level="DEBUG",  # 强制使用DEBUG级别，确保能看到所有日志
        colorize=True,
        backtrace=True,
        diagnose=True,
        enqueue=False  # 禁用队列以立即输出日志
    )
    
    # 添加主日志文件处理器
    logger.add(
        settings.log_file,
        format=file_format,
        level=settings.log_level,
        rotation="1 day",
        retention="30 days",
        compression="zip",
        backtrace=True,
        diagnose=True,
        encoding="utf-8"
    )
    
    # 添加错误日志文件
    error_log_file = log_dir / "error.log"
    logger.add(
        str(error_log_file),
        format=file_format,
        level="ERROR",
        rotation="1 day",
        retention="90 days",
        compression="zip",
        backtrace=True,
        diagnose=True,
        encoding="utf-8"
    )
    
    # 添加访问日志文件
    access_log_file = log_dir / "access.log"
    logger.add(
        str(access_log_file),
        format=file_format,
        level="INFO",
        rotation="1 day",
        retention="30 days",
        compression="zip",
        filter=lambda record: record.get("extra", {}).get("access", False),
        encoding="utf-8"
    )
    
    # 添加性能日志文件
    performance_log_file = log_dir / "performance.log"
    logger.add(
        str(performance_log_file),
        format=file_format,
        level="INFO",
        rotation="1 day",
        retention="7 days",
        compression="zip",
        filter=lambda record: "性能" in record["message"],
        encoding="utf-8"
    )
    
    # 创建全局日志记录器实例
    global_logger = CustomLogger("app")
    global_logger.info("自定义日志系统初始化完成")


def get_logger(name: str = None) -> CustomLogger:
    """获取日志记录器"""
    return CustomLogger(name or "app")


# 创建全局日志记录器实例
app_logger = get_logger("app")
